/**
 * 移库系统API服务类
 * 完全重构，参考JH拣货系统的成功架构
 */

import { WORKSHEET_IDS, API_CONFIG, WEBHOOK_CONFIG, FIELD_IDS, getConfigSnapshot, getEnvValue } from '../config/transfer-config.js'

// 输出配置快照用于调试
console.log('🔧 移库系统配置快照:', getConfigSnapshot());

class TransferApiService {
  constructor() {
    this._initialized = false
    this.init()
  }

  /**
   * 初始化配置
   */
  init() {
    console.log('移库系统API服务初始化...')
    
    this.WORKSHEET_IDS = WORKSHEET_IDS;
    this.API_CONFIG = API_CONFIG;
    this.FIELD_IDS = FIELD_IDS;
    this.webhookUrl = WEBHOOK_CONFIG.webhookUrl;
    
    console.log('初始化完成:', {
      工作表配置: {
        库位库存表: this.WORKSHEET_IDS.LOCATION_STOCK,
        移库单工作表: this.WORKSHEET_IDS.TRANSFER_ORDERS,
        库位管理工作表: this.WORKSHEET_IDS.LOCATION_MANAGEMENT
      },
      API配置: {
        baseURL: this.API_CONFIG.baseURL,
        appKey: (this.API_CONFIG.appKey && typeof this.API_CONFIG.appKey === 'string' && this.API_CONFIG.appKey.length > 6) ? `${this.API_CONFIG.appKey.slice(0,6)}***` : '❌ 未配置',
        sign: (this.API_CONFIG.sign && typeof this.API_CONFIG.sign === 'string' && this.API_CONFIG.sign.length > 6) ? `${this.API_CONFIG.sign.slice(0,6)}***` : '❌ 未配置'
      },
      Webhook配置: {
        webhookUrl: this.webhookUrl ? `${this.webhookUrl.slice(0, 30)}...` : '❌ 未配置'
      }
    });
    
    // ✅ 检查关键配置并给出明确警告
    if (!this.API_CONFIG.appKey || !this.API_CONFIG.sign) {
      console.error('🚨 严重警告: AppKey或Sign未配置，API调用将会失败！')
      console.error('请检查明道云环境配置中的以下变量:')
      console.error('- AppKey: 明道云应用密钥')
      console.error('- Sign: 明道云签名')
    } else {
      console.log('✅ API认证配置验证通过')
    }
    
    this._initialized = true
  }

  /**
   * 确保初始化
   */
  ensureInitialized() {
    if (!this._initialized) this.init()
  }

  /**
   * 安全的API调用封装 - 使用明道云标准调用方式
   */
  async callApi(method, params) {
    console.log(`📡 调用API: ${method}`, params);
    
    try {
      // 直接使用明道云标准API调用
      if (typeof window !== 'undefined' && window.api && window.api.call) {
        console.log(`📡 使用 window.api.call('worksheet', '${method}')`);
        
        // ✅ 添加Promise超时处理
        const apiPromise = window.api.call('worksheet', method, params);
        const timeoutPromise = new Promise((_, reject) => 
          setTimeout(() => reject(new Error('API调用超时(15秒)')), 15000)
        );
        
        const result = await Promise.race([apiPromise, timeoutPromise]);
        console.log(`📥 API响应成功 - 类型: ${typeof result}, 内容:`, result);
        
        // ✅ 检查结果有效性
        if (result === undefined || result === null) {
          console.warn('⚠️ API返回空结果');
          return { success: false, message: 'API返回空结果' };
        }
        
        return result;
      } else {
        const error = `window.api.call 不可用，当前环境: ${typeof window}`;
        console.error('❌', error);
        throw new Error(error);
      }
    } catch (error) {
      console.error(`❌ API调用失败 ${method}:`, {
        错误类型: error.constructor.name,
        错误消息: error.message,
        完整错误: error
      });
      throw error;
    }
  }

  /**
   * 暴露给外部调试使用的配置获取方法
   */
  getEnvValue(key) {
    return getEnvValue(key);
  }

  /**
   * 获取可用商品列表
   */
  async getAvailableProducts() {
    this.ensureInitialized()
    try {
      console.log('开始获取可用商品列表...')
      
      const response = await this.callApi('getFilterRows', {
        worksheetId: this.WORKSHEET_IDS.LOCATION_STOCK,
        pageSize: 200
      })
      
      if (response && response.data) {
        const products = new Set()
        response.data.forEach(row => {
          const productName = row[this.FIELD_IDS.PRODUCT_NAME]
          if (productName && productName.trim()) {
            products.add(productName.trim())
          }
        })
        
        const productList = Array.from(products).sort()
        console.log(`获取到 ${productList.length} 个商品:`, productList)
        return productList
      }
      
      return []
    } catch (error) {
      console.error('获取商品列表失败:', error)
      throw error
    }
  }

  /**
   * 根据商品名称搜索库位信息
   */
  async searchLocationsByProduct(productName) {
    this.ensureInitialized()
    try {
      if (!productName || !productName.trim()) {
        return []
      }

      const filters = [
        {
          filterId: this.FIELD_IDS.PRODUCT_NAME,
          values: [productName.trim()],
          dataType: 2,
          spliceType: 1
        }
      ]

      const response = await this.callApi('getFilterRows', {
        worksheetId: this.WORKSHEET_IDS.LOCATION_STOCK,
        filters: filters,
        pageSize: 200
      })
      
      if (response && response.data) {
        let locations = response.data.map(row => {
          console.log('🔍 库位搜索-数据库原始行数据:', row)
          console.log('🔍 库位搜索-字段映射检查:', {
            'SUPPLIER_NAME字段ID': this.FIELD_IDS.SUPPLIER_NAME,
            'PRODUCTION_DATE字段ID': this.FIELD_IDS.PRODUCTION_DATE,
            '供应商原始值': row[this.FIELD_IDS.SUPPLIER_NAME],
            '生产日期原始值': row[this.FIELD_IDS.PRODUCTION_DATE],
            '所有可用字段': Object.keys(row)
          })
          
          return {
            id: row.rowid,
            locationCode: row[this.FIELD_IDS.LOCATION_CODE] || '',
            productName: row[this.FIELD_IDS.PRODUCT_NAME] || '',
            supplierName: row[this.FIELD_IDS.SUPPLIER_NAME] || '',
            productionDate: row[this.FIELD_IDS.PRODUCTION_DATE] || '',
            lockedStock: parseInt(row[this.FIELD_IDS.LOCKED_STOCK] || '0'),
            stockQuantity: parseInt(row[this.FIELD_IDS.STOCK_QUANTITY] || '0'),
            rawData: row
          }
        })

        // 过滤掉库存为0的记录
        locations = locations.filter(loc => loc.lockedStock > 0)

        console.log(`商品 "${productName}" 找到 ${locations.length} 个可用库位:`, 
          locations.map(l => `${l.locationCode}(库存:${l.lockedStock})`))
        
        return locations
      }
      
      return []
    } catch (error) {
      console.error(`搜索商品库位失败 "${productName}":`, error)
      throw error
    }
  }

  /**
   * 验证库位编码是否存在
   */
  async validateLocationExists(locationCode) {
    this.ensureInitialized()
    try {
      if (!locationCode || !locationCode.trim()) {
        return false
      }

      console.log(`验证库位编码: "${locationCode}"`)
      
      const filters = [
        {
          filterId: this.FIELD_IDS.LOCATION_MANAGEMENT_CODE,
          values: [locationCode.trim()],
          dataType: 2,
          spliceType: 1
        }
      ]
      
      const response = await this.callApi('getFilterRows', {
        worksheetId: this.WORKSHEET_IDS.LOCATION_MANAGEMENT,
        filters: filters,
        pageSize: 1
      })
      
      const exists = response && response.data && response.data.length > 0
      console.log(`库位编码 "${locationCode}" ${exists ? '存在' : '不存在'}`)
      
      return exists
    } catch (error) {
      console.error(`验证库位编码失败 "${locationCode}":`, error)
      return false
    }
  }

  /**
   * 创建移库单
   */
  async createTransferOrder(transferData) {
    this.ensureInitialized()
    try {
      console.log('🔍 创建移库单 - 输入数据:', transferData)

      // ✅ 数据完整性验证
      if (!transferData.fromLocationCode?.trim()) {
        throw new Error('移出库位不能为空')
      }
      if (!transferData.toLocationCode?.trim()) {
        throw new Error('移入库位不能为空')
      }
      if (!transferData.quantity || transferData.quantity <= 0) {
        throw new Error('移库数量必须大于0')
      }
      if (!transferData.transferNumber?.trim()) {
        throw new Error('移库单号不能为空')
      }

      // 准备要提交的字段数据 - 确保所有值都是字符串格式
      const controls = [
        {
          controlId: this.FIELD_IDS.TRANSFER_TYPE,
          value: this.getTransferTypeName(transferData.transferType || 'normal') // ✅ 转换为中文显示名称
        },
        {
          controlId: this.FIELD_IDS.TRANSFER_NUMBER,
          value: String(transferData.transferNumber || '')
        },
        {
          controlId: this.FIELD_IDS.TRANSFER_STATUS,
          value: String(transferData.status || 'completed')
        },
        {
          controlId: this.FIELD_IDS.TRANSFER_FROM_LOCATION,
          value: String(transferData.fromLocationCode || '')
        },
        {
          controlId: this.FIELD_IDS.TRANSFER_TO_LOCATION,
          value: String(transferData.toLocationCode || '')
        },
        {
          controlId: this.FIELD_IDS.TRANSFER_QUANTITY,
          value: String(transferData.quantity || '0')
        }
      ].filter(control => control.value.trim() !== '') // ✅ 过滤空值

      console.log('🔍 API调用前的controls数据:', controls)
      console.log('🔍 工作表ID:', this.WORKSHEET_IDS.TRANSFER_ORDERS)
      
      // ✅ 验证必要配置
      if (!this.WORKSHEET_IDS.TRANSFER_ORDERS) {
        const error = '移库单工作表ID未配置，请检查 TRANSFER_ORDERS 配置'
        console.error('❌ 配置错误:', error)
        throw new Error(error)
      }
      
      console.log('✅ 工作表ID验证通过:', this.WORKSHEET_IDS.TRANSFER_ORDERS)

      const requestData = {
        worksheetId: this.WORKSHEET_IDS.TRANSFER_ORDERS,
        controls: controls
      }
      
      console.log('🔄 开始调用 addRowToWorksheet...')
      const result = await this.addRowToWorksheet(requestData)
      console.log('✅ addRowToWorksheet 调用完成，结果:', result)
      console.log('✅ 移库单创建成功:', result)
      
      // ✅ 确保返回结果包含必要的字段
      const rowid = result?.rowid || result?.data?.rowid || result?.data?.row_id || result?.data?.id || Date.now().toString()
      
      // ✅ 发送Webhook通知
      try {
        console.log('🔔 开始发送Webhook通知...')
        
        // 根据图片中的参数格式构建webhook数据
        console.log('🔍 Webhook构建 - transferData详细信息:', {
          transferData,
          生产日期: transferData.productionDate,
          供应商: transferData.supplierName,
          生产日期类型: typeof transferData.productionDate,
          供应商类型: typeof transferData.supplierName
        })
        
        const webhookData = {
          移库类型: this.getTransferTypeName(transferData.transferType),
          商品名称: transferData.productName,
          商品条码: transferData.productBarcode || '',
          生产日期: transferData.productionDate || '',
          移出库位: transferData.fromLocationCode,
          移入库位: transferData.toLocationCode, 
          移库数量: transferData.quantity,
          移库单号: transferData.transferNumber,
          供应商: transferData.supplierName || '',
          创建时间: new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit', 
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }).replace(/\//g, '/').replace(',', '')
        }
        
        console.log('🔍 Webhook最终数据:', webhookData)
        
        await this.sendWebhook(webhookData)
        console.log('✅ Webhook通知发送成功')
      } catch (webhookError) {
        console.warn('⚠️ Webhook通知发送失败，但不影响移库单创建:', webhookError.message)
        // webhook失败不影响主流程
      }
      
      // ✅ 返回标准化结果
      return {
        success: true,
        data: result?.data || result,
        rowid: rowid,
        transferId: rowid,
        message: '移库单创建成功'
      }
      
    } catch (error) {
      console.error('❌ 创建移库单失败:', error)
      return {
        success: false,
        error: error.message || '创建移库单失败',
        details: error
      }
    }
  }

  /**
   * 向工作表添加新记录 - 使用明道云内置API
   */
  async addRowToWorksheet(requestData) {
    this.ensureInitialized()
    try {
      console.log('📝 创建工作表记录:', requestData)
      
      // ✅ 使用明道云标准API调用方式
      console.log('🔍 尝试明道云标准API...');
      
      try {
        // 检查API环境
        console.log('🔍 检测明道云环境:', {
          windowApi: !!window.api,
          apiCall: !!(window.api && window.api.call),
          apiCallType: window.api && typeof window.api.call,
          windowKeys: Object.keys(window).filter(k => k.toLowerCase().includes('api')),
          mdyeKeys: window.mdye ? Object.keys(window.mdye) : '不存在'
        })
        
        if (!window.api || !window.api.call) {
          throw new Error(`明道云API环境不可用 - window.api: ${!!window.api}, window.api.call: ${!!(window.api && window.api.call)}`)
        }
        
        // ✅ 准备完整的API参数（包含认证信息）
        const apiParams = {
          appKey: this.API_CONFIG.appKey,
          sign: this.API_CONFIG.sign,
          worksheetId: requestData.worksheetId,
          controls: requestData.controls,
          triggerWorkflow: false // 根据文档添加此参数
        }
        
        console.log('📋 准备API参数:', {
          appKey: (apiParams.appKey && typeof apiParams.appKey === 'string' && apiParams.appKey.length > 8) ? `${apiParams.appKey.slice(0,8)}***` : '❌ 未配置',
          sign: (apiParams.sign && typeof apiParams.sign === 'string' && apiParams.sign.length > 8) ? `${apiParams.sign.slice(0,8)}***` : '❌ 未配置',
          worksheetId: apiParams.worksheetId,
          controlsCount: apiParams.controls.length,
          triggerWorkflow: apiParams.triggerWorkflow
        })
        
        console.log('📋 详细controls数据:', apiParams.controls)
        
        // 认证参数验证已移至headers构建后
        
        // ✅ 使用新的HTTP API调用方式
        console.log('🔄 开始HTTP API调用...')
        
        // 先验证AppKey和Sign是否真的有效
        console.log('🔍 验证认证参数实际值:', {
          appKey类型: typeof apiParams.appKey,
          appKey长度: apiParams.appKey ? apiParams.appKey.length : 0,
          appKey值: apiParams.appKey || '空值',
          sign类型: typeof apiParams.sign, 
          sign长度: apiParams.sign ? apiParams.sign.length : 0,
          sign值: apiParams.sign || '空值'
        })
        
        // ✅ 使用新的API端点进行HTTP请求
        const apiUrl = `https://www.dachen.vip/api/v3/app/worksheets/${apiParams.worksheetId}/rows`
        
        // ✅ 构建符合新API要求的请求体
        const requestBody = {
          triggerWorkflow: apiParams.triggerWorkflow || false,
          fields: apiParams.controls.map(control => ({
            id: control.controlId,
            value: control.value
          }))
        }
        
        // ✅ 构建请求头（包含认证信息）
        const headers = {
          'Content-Type': 'application/json',
          'HAP-AppKey': apiParams.appKey,
          'HAP-Sign': apiParams.sign
        }
        
        // ✅ 验证必需的认证头
        if (!headers['HAP-AppKey']) {
          throw new Error('HAP-AppKey未配置，无法进行API调用')
        }
        if (!headers['HAP-Sign']) {
          throw new Error('HAP-Sign未配置，无法进行API调用')
        }
        
        console.log('📡 发送HTTP请求:', {
          url: apiUrl,
          method: 'POST',
          headers: {
            'Content-Type': headers['Content-Type'],
            'HAP-AppKey': headers['HAP-AppKey'] ? `${headers['HAP-AppKey'].slice(0,8)}***` : '未配置',
            'HAP-Sign': headers['HAP-Sign'] ? `${headers['HAP-Sign'].slice(0,8)}***` : '未配置'
          },
          body: requestBody
        })
        
        try {
          const response = await Promise.race([
            fetch(apiUrl, {
              method: 'POST',
              headers: headers,
              body: JSON.stringify(requestBody)
            }),
            new Promise((_, reject) => 
              setTimeout(() => reject(new Error('HTTP请求超时(10秒)')), 10000)
            )
          ])
          
          console.log('📥 HTTP响应状态:', response.status, response.statusText)
          
          if (!response.ok) {
            const errorText = await response.text()
            console.error('❌ HTTP请求失败:', {
              status: response.status,
              statusText: response.statusText,
              errorText: errorText
            })
            throw new Error(`HTTP请求失败: ${response.status} ${response.statusText} - ${errorText}`)
          }
          
          const result = await response.json()
          console.log('✅ API调用成功!', result)
          
          // ✅ 标准化返回格式
          return {
            success: true,
            data: result?.data || result,
            rowid: result?.data?.id || result?.id || Date.now().toString()
          }
          
        } catch (error) {
          console.error('❌ HTTP请求失败:', error.message)
          console.error('📋 失败时的请求信息:', {
            url: apiUrl,
            requestBody: requestBody,
            headers: headers
          })
          throw error
        }
        
      } catch (error) {
        console.error('❌ 明道云API调用失败:', {
          error: error.message,
          stack: error.stack,
          worksheetId: requestData.worksheetId,
          controlsCount: requestData.controls.length
        })
        throw error
      }
      
    } catch (error) {
      console.error('创建工作表记录错误:', error)
      throw error
    }
  }

  /**
   * 获取移库单列表
   */
  async getTransferOrders(pageSize = 50) {
    this.ensureInitialized()
    try {
      console.log('获取移库单列表...')

      const response = await this.callApi('getFilterRows', {
        worksheetId: this.WORKSHEET_IDS.TRANSFER_ORDERS,
        pageSize: pageSize
      })
      
      if (response && response.data) {
        const transferOrders = response.data.map(row => ({
          id: row.rowid,
          transferType: row[this.FIELD_IDS.TRANSFER_TYPE] || '',
          transferNumber: row[this.FIELD_IDS.TRANSFER_NUMBER] || '',
          status: row[this.FIELD_IDS.TRANSFER_STATUS] || 'completed',
          fromLocationCode: row[this.FIELD_IDS.TRANSFER_FROM_LOCATION] || '',
          toLocationCode: row[this.FIELD_IDS.TRANSFER_TO_LOCATION] || '',
          quantity: parseInt(row[this.FIELD_IDS.TRANSFER_QUANTITY] || '0'),
          createTime: row[this.FIELD_IDS.TRANSFER_CREATE_TIME] || row.ctime || '',
          rawData: row
        }))

        console.log(`获取到 ${transferOrders.length} 条移库单记录`)
        return transferOrders
      }
      
      return []
    } catch (error) {
      console.error('获取移库单列表失败:', error)
      throw error
    }
  }

  /**
   * 按库位编码搜索商品
   */
  async searchByLocationCode(locationCode, transferType = '') {
    this.ensureInitialized()
    try {
      if (!locationCode || !locationCode.trim()) {
        return []
      }

      console.log(`按库位编码搜索商品: "${locationCode}"`)
      
      const filters = [
        {
          filterId: this.FIELD_IDS.LOCATION_CODE,
          values: [locationCode.trim()],
          dataType: 2,
          spliceType: 1
        }
      ]

      // 根据移库类型过滤库存
      if (transferType === 'bad-to-good') {
        // 残品转良：只从CP-01-01-01-01搜索
        filters[0].values = ['CP-01-01-01-01']
      }

      const response = await this.callApi('getFilterRows', {
        worksheetId: this.WORKSHEET_IDS.LOCATION_STOCK,
        filters: filters,
        pageSize: 200
      })
      
      if (response && response.data) {
        let results = response.data.map(row => {
          console.log('🔍 库位码搜索-数据库原始行数据:', row)
          console.log('🔍 库位码搜索-字段映射检查:', {
            'SUPPLIER_NAME字段ID': this.FIELD_IDS.SUPPLIER_NAME,
            'PRODUCTION_DATE字段ID': this.FIELD_IDS.PRODUCTION_DATE,
            '供应商原始值': row[this.FIELD_IDS.SUPPLIER_NAME],
            '生产日期原始值': row[this.FIELD_IDS.PRODUCTION_DATE],
            '所有可用字段': Object.keys(row)
          })
          
          return {
            id: row.rowid,
            locationCode: row[this.FIELD_IDS.LOCATION_CODE] || '',
            productName: row[this.FIELD_IDS.PRODUCT_NAME] || '',
            barcode: row[this.FIELD_IDS.PRODUCT_BARCODE] || '',
            supplierName: row[this.FIELD_IDS.SUPPLIER_NAME] || '',
            productionDate: row[this.FIELD_IDS.PRODUCTION_DATE] || '',
            lockedStock: parseInt(row[this.FIELD_IDS.LOCKED_STOCK] || '0'),
            stockQuantity: parseInt(row[this.FIELD_IDS.STOCK_QUANTITY] || '0'),
            availableStock: parseInt(row[this.FIELD_IDS.AVAILABLE_STOCK] || row[this.FIELD_IDS.LOCKED_STOCK] || '0'),
            rawData: row
          }
        })

        // 过滤掉库存为0的记录
        results = results.filter(item => 
          (item.availableStock > 0) || (item.lockedStock > 0) || (item.stockQuantity > 0)
        )

        console.log(`库位 "${locationCode}" 找到 ${results.length} 个有库存的商品`)
        return results
      }
      
      return []
    } catch (error) {
      console.error(`按库位搜索失败 "${locationCode}":`, error)
      throw error
    }
  }

  /**
   * 按商品条码搜索
   */
  async searchByBarcode(barcode, transferType = '') {
    this.ensureInitialized()
    try {
      if (!barcode || !barcode.trim()) {
        return []
      }

      console.log(`按商品条码搜索: "${barcode}"`)
      
      const filters = [
        {
          filterId: this.FIELD_IDS.PRODUCT_BARCODE,
          values: [barcode.trim()],
          dataType: 2,
          spliceType: 1
        }
      ]

      const response = await this.callApi('getFilterRows', {
        worksheetId: this.WORKSHEET_IDS.LOCATION_STOCK,
        filters: filters,
        pageSize: 200
      })
      
      if (response && response.data) {
        let results = response.data.map(row => {
          console.log('🔍 条码搜索-数据库原始行数据:', row)
          console.log('🔍 条码搜索-字段映射检查:', {
            'SUPPLIER_NAME字段ID': this.FIELD_IDS.SUPPLIER_NAME,
            'PRODUCTION_DATE字段ID': this.FIELD_IDS.PRODUCTION_DATE,
            '供应商原始值': row[this.FIELD_IDS.SUPPLIER_NAME],
            '生产日期原始值': row[this.FIELD_IDS.PRODUCTION_DATE],
            '所有可用字段': Object.keys(row)
          })
          
          return {
            id: row.rowid,
            locationCode: row[this.FIELD_IDS.LOCATION_CODE] || '',
            productName: row[this.FIELD_IDS.PRODUCT_NAME] || '',
            barcode: row[this.FIELD_IDS.PRODUCT_BARCODE] || '',
            supplierName: row[this.FIELD_IDS.SUPPLIER_NAME] || '',
            productionDate: row[this.FIELD_IDS.PRODUCTION_DATE] || '',
            lockedStock: parseInt(row[this.FIELD_IDS.LOCKED_STOCK] || '0'),
            stockQuantity: parseInt(row[this.FIELD_IDS.STOCK_QUANTITY] || '0'),
            availableStock: parseInt(row[this.FIELD_IDS.AVAILABLE_STOCK] || row[this.FIELD_IDS.LOCKED_STOCK] || '0'),
            rawData: row
          }
        })

        // 过滤掉库存为0的记录
        results = results.filter(item => 
          (item.availableStock > 0) || (item.lockedStock > 0) || (item.stockQuantity > 0)
        )

        // 根据移库类型过滤
        if (transferType === 'bad-to-good') {
          // 残品转良：只显示CP-01-01-01-01的库存
          results = results.filter(item => item.locationCode === 'CP-01-01-01-01')
        }

        console.log(`条码 "${barcode}" 找到 ${results.length} 个有库存的商品`)
        return results
      }
      
      return []
    } catch (error) {
      console.error(`按条码搜索失败 "${barcode}":`, error)
      throw error
    }
  }

  /**
   * 获取移库类型名称
   */
  getTransferTypeName(type) {
    const typeNames = {
      'normal': '普通移库',
      'good-to-bad': '良品转残',
      'bad-to-good': '残品转良'
    }
    return typeNames[type] || '未知类型'
  }

  /**
   * 获取状态名称
   */
  getStatusName(status) {
    const statusNames = {
      'pending': '待处理',
      'executing': '执行中',
      'completed': '已完成',
      'cancelled': '已取消',
      'failed': '失败'
    }
    return statusNames[status] || '未知状态'
  }

  /**
   * 验证移库数据
   */
  async validateTransferDataAsync(transferData) {
    try {
      console.log('🔍 验证函数接收到的数据:', {
        transferType: transferData.transferType,
        productName: transferData.productName,
        quantity: transferData.quantity,
        fromLocation: transferData.fromLocation,
        fromLocation类型: typeof transferData.fromLocation,
        fromLocationLocationCode: transferData.fromLocation?.locationCode,
        toLocationCode: transferData.toLocationCode
      });
      
      const errors = []
      
      // 检查必填字段
      if (!transferData.productName?.trim()) {
        errors.push('请选择商品')
      }
      
      if (!transferData.quantity || transferData.quantity <= 0) {
        errors.push('请输入有效的移库数量')
      }
      
      // 检查库位
      if (transferData.transferType === 'normal') {
        console.log('🔍 普通移库验证 - fromLocation检查:', {
          fromLocation存在: !!transferData.fromLocation,
          locationCode存在: !!transferData.fromLocation?.locationCode,
          locationCode值: transferData.fromLocation?.locationCode,
          locationCode长度: transferData.fromLocation?.locationCode?.length,
          trim后: transferData.fromLocation?.locationCode?.trim()
        });
        
        if (!transferData.fromLocation?.locationCode?.trim()) {
          console.warn('❌ fromLocation验证失败');
          errors.push('请选择移出库位')
        }
        if (!transferData.toLocationCode?.trim()) {
          errors.push('请输入移入库位')
        }
      } else if (transferData.transferType === 'bad-to-good') {
        if (!transferData.toLocationCode?.trim()) {
          errors.push('请输入移入库位')
        }
      }
      
      return {
        isValid: errors.length === 0,
        errors: errors
      }
    } catch (error) {
      return {
        isValid: false,
        errors: ['数据验证过程中发生错误: ' + error.message]
      }
    }
  }

  /**
   * 测试库位管理表连接
   */
  async testLocationManagementConnection() {
    this.ensureInitialized()
    try {
      console.log('🔍 测试库位管理表连接...')
      
      const response = await this.callApi('getFilterRows', {
        worksheetId: this.WORKSHEET_IDS.LOCATION_MANAGEMENT,
        pageSize: 5
      })
      
      if (response && response.data) {
        console.log('✅ 库位管理表连接成功，样例数据:', response.data.slice(0, 2))
        return {
          success: true,
          recordCount: response.data.length,
          message: `连接成功，找到 ${response.data.length} 条记录`
        }
      } else {
        return {
          success: false,
          error: '响应数据为空'
        }
      }
    } catch (error) {
      console.error('❌ 库位管理表连接失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 检测库位编码字段ID
   */
  async detectLocationFieldId() {
    this.ensureInitialized()
    try {
      console.log('🔍 开始检测库位编码字段ID...')
      
      const response = await this.callApi('getFilterRows', {
        worksheetId: this.WORKSHEET_IDS.LOCATION_MANAGEMENT,
        pageSize: 3
      })
      
      if (response && response.data && response.data.length > 0) {
        const sampleRow = response.data[0]
        console.log('📋 样例记录结构:', sampleRow)
        
        // 查找可能包含库位编码的字段
        const possibleFields = []
        Object.keys(sampleRow).forEach(fieldId => {
          const value = sampleRow[fieldId]
          if (typeof value === 'string' && value.match(/^[A-Z]{1,3}-?\d{2}-?\d{2}-?\d{2}-?\d{2}$/)) {
            possibleFields.push({
              fieldId: fieldId,
              value: value,
              pattern: '库位编码格式'
            })
          }
        })
        
        console.log('🎯 检测到可能的库位编码字段:', possibleFields)
        
        if (possibleFields.length > 0) {
          return possibleFields[0].fieldId
        } else {
          console.warn('⚠️ 未找到匹配的库位编码字段')
          return null
        }
      }
      
      return null
    } catch (error) {
      console.error('❌ 字段ID检测失败:', error)
      return null
    }
  }

  /**
   * 测试移库单工作表连接
   */
  async testTransferWorksheetConnection() {
    this.ensureInitialized()
    try {
      console.log('🔍 测试移库单工作表连接...')
      
      const response = await this.callApi('getFilterRows', {
        worksheetId: this.WORKSHEET_IDS.TRANSFER_ORDERS,
        pageSize: 5
      })
      
      if (response && response.data) {
        console.log('✅ 移库单工作表连接成功，样例数据:', response.data.slice(0, 2))
        return {
          success: true,
          recordCount: response.data.length,
          message: `连接成功，找到 ${response.data.length} 条记录`
        }
      } else {
        return {
          success: false,
          error: '响应数据为空'
        }
      }
    } catch (error) {
      console.error('❌ 移库单工作表连接失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 验证移库单字段映射
   */
  async validateTransferFieldMapping() {
    this.ensureInitialized()
    try {
      console.log('🔍 开始验证移库单字段映射...')
      
      const response = await this.callApi('getFilterRows', {
        worksheetId: this.WORKSHEET_IDS.TRANSFER_ORDERS,
        pageSize: 1
      })
      
      if (response && response.data && response.data.length > 0) {
        const sampleRow = response.data[0]
        console.log('📋 移库单样例记录结构:', Object.keys(sampleRow))
        
        const fieldMapping = {
          '移库类型': this.FIELD_IDS.TRANSFER_TYPE,
          '移库单号': this.FIELD_IDS.TRANSFER_NUMBER,
          '移库状态': this.FIELD_IDS.TRANSFER_STATUS,
          '移出库位': this.FIELD_IDS.TRANSFER_FROM_LOCATION,
          '移入库位': this.FIELD_IDS.TRANSFER_TO_LOCATION,
          '移库数量': this.FIELD_IDS.TRANSFER_QUANTITY
        }
        
        const validFields = []
        const invalidFields = []
        
        Object.entries(fieldMapping).forEach(([fieldName, fieldId]) => {
          if (sampleRow.hasOwnProperty(fieldId)) {
            validFields.push(`${fieldName}(${fieldId})`)
          } else {
            invalidFields.push(`${fieldName}(${fieldId})`)
          }
        })
        
        console.log('✅ 有效字段:', validFields)
        console.log('❌ 无效字段:', invalidFields)
        
        return {
          success: true,
          allFieldsExist: invalidFields.length === 0,
          validFields: validFields,
          invalidFields: invalidFields,
          message: `字段验证完成: ${validFields.length}个有效，${invalidFields.length}个无效`
        }
      } else {
        return {
          success: false,
          error: '无法获取样例记录进行字段验证'
        }
      }
    } catch (error) {
      console.error('❌ 字段映射验证失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 构建附加移库字段
   */
  async buildAdditionalTransferFields(transferData) {
    try {
      const additionalFields = []
      
      // 可以在这里添加任何需要的附加字段映射
      if (transferData.productName) {
        // 示例：可以添加商品名称映射等
        console.log('构建附加字段，商品名称:', transferData.productName)
      }
      
      return additionalFields
    } catch (error) {
      console.error('构建附加字段失败:', error)
      return []
    }
  }

  /**
   * 生成移库单号
   */
  generateTransferNumber() {
    const now = new Date()
    const dateStr = 
      String(now.getFullYear()) +
      String(now.getMonth() + 1).padStart(2, '0') +
      String(now.getDate()).padStart(2, '0')
    const timeStr = 
      String(now.getHours()).padStart(2, '0') +
      String(now.getMinutes()).padStart(2, '0') +
      String(now.getSeconds()).padStart(2, '0')
    return `YK${dateStr}${timeStr}`
  }

  /**
   * 发送Webhook通知
   */
  async sendWebhook(data) {
    this.ensureInitialized()
    try {
      if (!this.webhookUrl || !this.webhookUrl.trim()) {
        console.warn('⚠️ Webhook URL未配置，跳过通知发送')
        return { success: false, reason: 'Webhook URL未配置' }
      }

      console.log('🔔 发送Webhook通知到:', this.webhookUrl)
      console.log('📋 Webhook数据:', data)

      const response = await Promise.race([
        fetch(this.webhookUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        }),
        new Promise((_, reject) => 
          setTimeout(() => reject(new Error('Webhook请求超时(10秒)')), 10000)
        )
      ])

      console.log('📥 Webhook响应状态:', response.status, response.statusText)

      if (!response.ok) {
        const errorText = await response.text()
        console.error('❌ Webhook请求失败:', {
          status: response.status,
          statusText: response.statusText,
          errorText: errorText
        })
        throw new Error(`Webhook请求失败: ${response.status} ${response.statusText}`)
      }

      // 尝试解析响应，如果不是JSON也不报错
      let result = {}
      try {
        result = await response.json()
      } catch {
        result = { message: 'Webhook响应不是JSON格式' }
      }
      
      console.log('✅ Webhook发送成功:', result)
      return { success: true, result: result }

    } catch (error) {
      console.error('❌ Webhook发送失败:', {
        错误类型: error.constructor.name,
        错误消息: error.message,
        WebhookURL: this.webhookUrl
      })
      throw error
    }
  }
}

// 创建单例实例
const transferApi = new TransferApiService()

// 导出单例
export default transferApi